import { VueComponent, Prop,Watch } from 'vue-typescript'
import { azureBlob } from '../../service/azure-blob-upload'
import {dataService} from '../../service/dataService'
import * as VueRouter from 'vue-router'
Vue.use(VueRouter);
var router = new VueRouter();
var moment = require('moment');
var VueTables = require('vue-tables');
Vue.use(VueTables.client,{
    filterable:false,
    compileTemplates:true,
    pagination: {
     dropdown:false,
    },
    texts:{
     count:'{count} 条',
    }
    
});
@VueComponent({
    template: require('./inquiryAdd.html'),
})
export class InquiryAddComponent extends Vue {
    el:'#inquiryAddEl'
    components:({
        vclienttable:any,
    })
    columns=['id','shipAddress','deliveryAddress','goodsName','goodsQuantity','plannedDeliveryTime','plannedArrivalTime','carType','carLength','operation']
    @Prop
    router=new VueRouter();
    tableData= []
    inquiryChildList=[];
    options= {
    headings:{
        id:"序号",
        deliveryAddress:"送货地址",
        shipAddress:"发货地址",
        goodsName:"货物名称",
        goodsQuantity:"货物数量",
        plannedArrivalTime:"预计到货时间",
        plannedDeliveryTime:"预计发货时间",
        carType:"所需车型",
        carLength:"所需车长",
        operation:'操作'
    },
    templates: {
        operation: function(row) {
          return `<a class='glyphicon glyphicon-trash primary text-danger m-l-xs' title='删除' href='javascript:void(0);' @click='$parent.deleteMe(${row.index})'></a>`
        }
      },
    };
    sortable=[];
    deleteMe=function(index){
        //调后台接口(删除)
        // console.info('test');
        //本地(删除子询价)
        var itemDel = this.tableData.filter(t => t.index == index)
        this.tableData.$remove(itemDel[0])
        var inquiryChildListItemDel=this.inquiryChildList.filter(t=>t.index==index);
        this.inquiryChildList.$remove(inquiryChildListItemDel[0]);
    }
    package:string = 'vue-typescript';
    repo:string = 'https://github.com/itsFrank/vue-typescript';

    
    //v-model初始化
    inquiryChildCode:string=''
    inquiryTime:string=''
    urgency:string='';
    urgencyUnit:string='';
    consignor:string='';
    consignorPhone:string='';
    content:string='';
    starProvince:string='';
    starCity:string='';
    starAreaCity:string='';
    startAddress:string='';
    endProvince:string='';
    endCity:string='';
    endArea:string='';
    endAddress:string='';
    plannedArrivalTime:string="";
    plannedDeliveryTime:string=''
    goodsTypeId:string="";
    goodsId:string=''
    goodsQuantity:string=''
    goodsQuantityUnit:string=''
    carType:string=''
    carLength:string=''
    carrierCategory:string=''
    loadingEffect:string=''
    attachmentDetails:string=''
    //设置禁用（详情）
    titleInquiry:string='询价单详情'
    //sasUrl
    @Prop
    showLinkToInquiry:boolean=false;
    inquiryChildIdLinkTo:string='';
    sasUrl:string='';
    starProvinceList=[];
    starCityList=[];
    starAreaList=[];
    endProvinceList=[];
    endCityList=[];
    endAreaList=[];
    goodsQuantityUnitDropDown=[{"text": "吨","value": "1"},{"text": "立方","value": "2"},{ "text": "车","value": "3"},{"text": "件","value": "4"},{"text": "托","value": "5"},{"text": "台","value": "6"},{"text": "其他","value": "7"}]
    carTypeDropDown=[{"text": "厢车","value": "1"},{"text": "飞翼","value": "2"},{"text": "半挂","value": "3"},{"text": "标厢","value": "4"}, {"text": "大平板","value": "5"},{"text": "平板","value": "6"},{"text": "高低板","value": "7"},{"text": "高栏平板","value": "8"},{"text": "高栏高低板", "value": "9"},{"text": "大件车抽拉板", "value": "10"},{ "text": "大件车超低板", "value": "11"},{"text": "自卸车","value": "12"},{"text": "单车","value": "13"},{"text": "其他", "value": "14" }]
    carLengthDropDown=[{ "text": "4.2米","value": "1"},{"text": "5.8米","value": "2"}, {"text": "6米","value": "3"}, { "text": "6.2米","value": "4" }, { "text": "6.5米", "value": "5"},  {"text": "6.8米","value": "6" }, {"text": "7.6米","value": "7"},{"text": "8.6米","value": "8"},{ "text": "8.7米","value": "9"},{"text": "9.6米","value": "10"},{ "text": "13米", "value": "11"},{"text": "13.5米","value": "12" },{"text": "16米","value": "13"},{"text": "17.5米","value": "14" }, {"text": "其他","value": "15"}]
    carrierCategoryDropDown=[{"text": "整车","value": "1"},{"text": "零担", "value": "2" }, {"text": "整车/零担","value": "3"}] 
    urgencyUnitDropDown=[{text:"天",value:"1"},{text:"时",value:"2"},{text:"分",value:"3"}];
    goodsTypeDropDown=[];
    goodsNameDropDown=[];
    consignorDropDown=[];
    // https://sinostoragedev.blob.core.chinacloudapi.cn/avatar-container?sv=2016-05-31&sr=c&sig=nUNfvCUrZ%2F%2Bjuc%2Fesjjl0tXw7nY4E4JJJ8jD7PBSUjI%3D&st=2017-01-26T06%3A19%3A15Z&se=2017-01-27T06%3A24%3A15Z&sp=racwl
    
    imageLists=[];
    //提交的图片数据
    submitImageLists=[];
    uploadDisabled=this.imageLists.length>0;
    object:{default:string} = {default: 'Default object property!'}; //objects as default values don't need to be wrapped into functions
    imageColumns =['image','name','size','rate','state','operation'];
    imageOptions= {
    headings:{
        image:'图片',
        name:"名称",
        size:"大小",
        rate:"进度",
        state:"状态",
        operation:'操作'
    },
    templates: {
        operation: (row)=> {
            // console.info('showStatus',row.showStatus);
            var operationDelTemple=`<a title='删除' href='javascript:void(0);' @click='$parent.deleteImage(${row.id})' class="btn"><i class='glyphicon glyphicon-trash  primary text-danger m-l-xs'></i></a>`
            var operationUploadTemple=`<a class='btn' title='上传' id="${row.id}uploadDisabledStatus" href='javascript:void(0);' @click='$parent.uploadImage(${row.id})'><i class='glyphicon glyphicon-upload'></i></a>`;
            var operationDownloadTemple=`<a class='btn' title='下载' href='javascript:void(0);'  @click='$parent.downloadImage(${row.id})'><i class='glyphicon glyphicon-download text-success'></i></a>`
            if(row.showStatus){
            if(this.submitImageLists.length>0){
                if(this.submitImageLists.filter(t=>t.id==row.id).length>0){
                    if(this.submitImageLists.filter(t=>t.id==row.id)[0].submitUrl){
                        return operationDelTemple+
                            `<a class='btn' title='上传' id="${row.id}uploadDisabledStatus" href='javascript:void(0);' @click='$parent.uploadImage(${row.id})' disabled="disabled"><i class='glyphicon glyphicon-upload'></i></a>`
                    }
                }else{return operationDelTemple+operationUploadTemple;}
            }else{return operationDelTemple+operationUploadTemple;}
            }else{return operationDownloadTemple;}
        },
        image:(row)=>{
            if(row.showStatus){
                //add
                if(row.type.indexOf("image")>=0){
                    //图片
                    return `<div class="img-thumbnail" style="position:relative">
                        <img class="img-responsive" src="${row.path}" style="width:236px;height:298px" />
                    </div>`;
                }else{
                    //非图片
                    return `<i>${row.name}<i>`;
                }
            }else{
                //详情
                if(!/gif|jpeg|jpg|png|bmp/.test(row.path.substring(row.path.indexOf(".")))){
                   var test= row.path.split("/");
                   var fileName=test[(test.length)-1];
                   return `<i>${fileName}<i>`;
                }else{
                    return `<div class="img-thumbnail" style="position:relative">
                        <img class="img-responsive" src="${row.path}" style="width:236px;height:298px" />
                    </div>`;
                }
            }
        },
        state:(row)=>{
            var stateTemple=`<span class='glyphicon glyphicon-remove text-danger' id="${row.id}"  title='状态显示'></span>`;
            var stateTempleSuccess=`<span class='glyphicon glyphicon-ok text-success' id="${row.id}"  title='状态显示'></span>`;
            if(row.showStatus){
                if(this.submitImageLists.length>0){
                    if(this.submitImageLists.filter(t=>t.id==row.id).length>0){
                        if(this.submitImageLists.filter(t=>t.id==row.id)[0].submitUrl){return stateTempleSuccess;}
                    }else{return stateTemple;}
                }else{return stateTemple;}
            }else{return stateTempleSuccess;}
        },
        rate:(row)=>{
            var rateTemple =`<div class="progress"><div class="progress-bar progress-bar-uploadFile" id='${row.id}progressBar' role="progressbar"></div></div>`;
            var rateTempleSuccess=`<div class="progress"><div class="progress-bar progress-bar-uploadFile" id='${row.id}progressBar' role="progressbar" style="width:100.00%"></div></div>`;
            // console.info(this.submitImageLists)
                if(row.showStatus){
                    if(this.submitImageLists.length>0){
                        if(this.submitImageLists.filter(t=>t.id==row.id).length>0){
                            if(this.submitImageLists.filter(t=>t.id==row.id)[0].submitUrl){return rateTempleSuccess;}
                        }else{return rateTemple;}
                    }else{return rateTemple;}
            }else{return rateTempleSuccess;}
        }
      },
    };
    //下载附件
    downloadImage=function(index){
        var url = this.imageLists.filter(t => t.id == index)[0].path;
        // window.location.href = url;
         // Get file name from url.
        var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function () {
            var a = document.createElement('a');
            a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
            // a.download = filename; // Set the file name.
            a.setAttribute("download",filename);
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            a=null;
        };
        xhr.open('GET', url);
        xhr.send();
    }
    //del img
    deleteImage=function(index){
        // console.info(index);
        var itemDel = this.imageLists.filter(t => t.id == index)
        var submitItemDel= this.submitImageLists.filter(t => t.id == index);
        // console.info(this.imageLists);
        this.imageLists.$remove(itemDel[0]);
        this.submitImageLists.$remove(submitItemDel[0]);
        if(this.imageLists.length<=0){
            $('#inquiryAdd_uploadAll').attr('disabled', 'true');
        }
    }
    
    //uploade img
    uploadImage=function(id){
        //${row.id}uploadDisabledStatus
        var uploadDisabledStatus = $("#"+id+'uploadDisabledStatus').attr('disabled');
        // console.info('uploadDisabledStatus','disabled');
        if(uploadDisabledStatus!=='disabled'){
            //未上传（该图片）
            var submitUrl='';
            var itemUpload =this.imageLists.filter(t => t.id == id);
            var baseUrl = this.sasUrl;
            var indexOfQueryStart = baseUrl.indexOf("?");
            // $('#enlargeImage' + imageName).attr('href', objUrl);

            var today = new Date();
            // var formatDate = $filter('date')(today, 'yyyyMMddHHmms');
            var formatDate=moment().format('YYYYMMDDHHmm');
            var rr = itemUpload[0].name.indexOf(".");
            var nameimg = formatDate + Math.round(Math.random() * 10000).toString() + itemUpload[0].name.substring(rr);
            submitUrl= baseUrl.substring(0, indexOfQueryStart) + '/' + nameimg + baseUrl.substring(indexOfQueryStart);
            // itemUpload[0].name=nameimg;
            this.upload(submitUrl,itemUpload[0], nameimg.split(".", 1).join());
        }
    }
    //上传图片
    upload=function(submitUri, selectedFile, nameimg){
        // azureBlob.upload
        azureBlob().upload({
                baseUrl: submitUri,
                sasToken: 'avatar-container',
                file: selectedFile,
                progress: function (data, status) {
                    // console.log('test progress data', data);
                    // console.log('test progress status', status);
                    $("#"+selectedFile.id+'progressBar').attr({style:"width:"+data+'%'});
                },
                complete:  (data, status)=> {
                    // console.log('test complete data', data);
                    // console.log('test complete status', status);
                    // console.info('result', nameimg);
                    // var imageUriSubmit = encodeURIComponent(submitUri.split("?", 1).join());
                    var imageUriSubmit = submitUri.split("?", 1).join();
                    selectedFile.fileName=nameimg;
                    selectedFile.submitUrl=imageUriSubmit;
                    // this.submitImageLists=[];
                    // this.submitImageLists.splice(0,this.submitImageLists.length); 
                    // console.info('selectedFile.id+"state"',selectedFile.id+"state");
                    $("#"+selectedFile.id).attr("class","glyphicon glyphicon-ok text-success");
                    $("#"+selectedFile.id+'uploadDisabledStatus').attr('disabled','disabled');
                    this.submitImageLists.push(selectedFile);
                },
                error: function (xhr, desc, err) {
                    // console.log('test error desc', desc);
                    // console.log('test error err', err);
                },
                blockSize: 1024 * 32,
            });
    }
    //全部上传
    attachmentUploader=()=>{
        for(var i=0;i<this.imageLists.length;i++){
            this.uploadImage(this.imageLists[i].id);
        }
    }
    @Prop
    inquiryId:string;
    name:string;
    customerUnit:string='';
    enterpriseid:string;
    customerId:string='';
    //uploader image
    ready(){
        //初始设置
       this.inquiryChildCode='';
       this.inquiryTime='';
       this.urgency='';
       this.urgencyUnit='';
    //    this.customerUnit='';
       this.consignor='';
       this.consignorPhone='';
       this.content='';
       this.starProvince='';
       this.starCity='';
       this.starAreaCity='';
       this.startAddress='';
       this.endProvince='';
       this.endCity='';
       this.endArea='';
       this.endAddress='';
       this.plannedArrivalTime='';
       this.plannedDeliveryTime='';
       this.goodsTypeId='';
       this.goodsId='';
       this.goodsQuantity='';
       this.goodsQuantityUnit='';
       this.carType='';
       this.carLength='';
       this.carrierCategory='';
       this.loadingEffect=''
       this.attachmentDetails='';
       //表格设置
       //发布提交 子询价列表 初始设置 空
       this.inquiryChildList=[];
       //发布提交 附件列表 初始设置 空
    //    this.submitImageLists=[];
       this.submitImageLists.splice(0,this.submitImageLists.length);
       //附件表格 初始显示  空
       this.imageLists==[];
    //    this.imageLists.splice(0,this.imageLists.length);
       //子询价列表 初始显示 空
       this.tableData=[];
       //前往该询价单..是否显示
       this.showLinkToInquiry=false;
       //end 初始设置

        this.imageLists=[];
        //客户单位初始化
        this.customerUnit = JSON.parse(window.sessionStorage.getItem("userInfo")).realName;
        // this.enterpriseid = JSON.parse(window.sessionStorage.getItem("userInfo")).id;
        this.enterpriseid = '';
        // console.info('$route.path',this.$route.path);
        var a=this.$route.path;var b = a.substring(a.indexOf("="));var c=b.split("=");
        this.name=c[2];
        // console.info('name',name)
        var dd=c[1].split("&");
        this.inquiryId=dd[0];
        // console.info('inquiryId',inquiryId);
        
        if(this.name=="copy"||this.name=="add"){
            this.titleInquiry = '询价单新增';
        }else if(this.name=="detail"||this.name=="edit"){
            this.titleInquiry = '询价单详情';
            if(this.name=="edit"){
                this.showLinkToInquiry=true;
            }
            $('#fieldsetDisabled').attr('disabled', 'disabled');
            $("#fieldsetDisabledTwo").attr('disabled', 'disabled');
        }
        
        dataService().CustomerRepresentative.getCustomerList('',0,5).then((res)=>{
            this.consignorDropDown=res.data;
        })
        //获取货物类别列表
        dataService().GoodsType.getDoodsTypeList(this.inquiryId,0,-1).then((res)=>{
            this.goodsTypeDropDown=res.data;
        })
        //获取省列表
        dataService().Area.getProvince().then((res)=>{
            this.starProvinceList=res.list;
            this.endProvinceList=res.list;
        })
        
        // $('#realHead').bind('change', 'RealHead', this.handleFileSelect);

        //时间插件 初始化
        $('#dataTime').datetimepicker({format:  'YYYY.MM.DD HH:mm'});
        $("#dataTimeEnd").datetimepicker({format:  'YYYY.MM.DD HH:mm'});
        // 获取发布询价详情
        if( this.inquiryId!=="undefined"&& this.inquiryId && this.name!=='add'){
            // this.inquiryId="8ca04016-da77-4191-8301-54445c7910cf"
            dataService().CspInquiry.getCspInquiry(this.inquiryId).then((res)=>{
                //子询价编号
                this.inquiryChildCode=res.cspInquiryChildCode;
                //询价发布时间
                this.inquiryTime=res.cspInquiryTime
                //客户单位
                this.customerUnit=res.clientName
                //发货计划人
                this.customerId = this.consignorDropDown.filter(t=>t.realName==res.customerName)[0].id;
                this.consignor=res.customerName
                //发货人电话
                this.consignorPhone=res.customerPhone
                //总询价内容
                this.content=res.content
                //发货目的地
                this.getAllAreaEnd(res.destinationProvince,res.destinationCity,true);
                this.endProvince=res.destinationProvince
                // this.getEndProvinceList();
                this.endCity=res.destinationCity
                // this.getEndCityList();
                this.endArea=res.destinationCounty
                this.endAddress=res.destinationDetails
                //发货起始地
                this.getAllAreaStart(res.originProvince,res.originCity,true);
                this.starProvince=res.originProvince
                // this.getStarProvinceList();
                this.starCity=res.originCity;
                // this.getCityList();
                this.starAreaCity=res.originCounty
                this.startAddress=res.originDetails
                //（到货时间）
                this.plannedDeliveryTime= res.foreDeliveryTime;//到货
                //（发货时间）
                this.plannedArrivalTime= res.foreArrivalTime;//发货
                //货物类别name "00c58a35-c501-414d-b0bb-937c9f53f3dc"  getCustomerList
                this.goodsTypeId=res.goodsTypeId
                this.goodsTypeSelect();
                //货物name
                this.goodsId=res.goodsId
                //货物数量
                this.goodsQuantity=res.quantityOfGoods
                //货物数量单位
                this.goodsQuantityUnit=res.goodsUnit
                //车型
                this.carType=res.vehicleType
                //车长
                this.carLength=res.carLength
                //承运发式
                this.carrierCategory=res.carriageWay
                //装车效果
                this.loadingEffect=res.loadingEffect
                //附件备注
                this.attachmentDetails=res.attachmentRemarks
                //紧急程度
                this.urgency=res.responseTime;
                //紧急程度单位
                this.urgencyUnit=res.responseTimeUnit;
                //附件列表
                if(this.name=='detail'||this.name=='edit'){
                    if(res.attachmentList){
                        res.attachmentList.forEach((item,index)=>{
                            item.id=index.toString();
                            item.showStatus=false;
                            this.imageLists.push(item);
                        })
                    }
                }
                // res.attachmentList[0].id
                // res.attachmentList[0].name
                // res.attachmentList[0].path
                // res.attachmentList[0].tag
                this.inquiryChildIdLinkTo= res.inquiryChildId;

                // console.info('res:',res);
            },(rej)=>{
                // console.info('rej:',rej);
            })
        }
        //获取sasurl
        dataService().Storage.AquireStorageSharedSigniture().then((res)=>{
            this.sasUrl=res.storageSharedSigniture;
        })
        // this.getStarProvinceList();
        // this.getCityList();
        // this.getEndProvinceList();
        // this.getEndCityList();
    }
   
    //选择发货计划人 触发
    changeConsignor=function(){
        this.consignorPhone=this.consignorDropDown.filter(t=>t.realName==this.consignor)[0].phoneNumber;
        this.customerId=this.consignorDropDown.filter(t=>t.realName==this.consignor)[0].id;
    }
     //选中货物类别 触发 货物列表
     // 下拉选择框 select onChange
    goodsTypeSelect=function() {
        if(this.goodsTypeId){
            dataService().Goods.getDoodsList('',this.goodsTypeId,0,-1).then((res)=>{
                this.goodsNameDropDown=res.data;
                // console.info('res:',res);
            },function(rej){
                // console.info('rej:',rej);
            })
        }
    }
    //总Arealist start
    getAllAreaStart=function(p:string,c:string,t:boolean) {
        dataService().Area.getAllArea(p,c,t).then((resAreaStart)=>{
            // console.info('resAreastart',resAreaStart);
            this.starProvinceList=resAreaStart.province;
            this.starCityList  = resAreaStart.city;//市
            this.starAreaList = resAreaStart.county;//区
        })
    }
    // 总Arealist end 
    getAllAreaEnd=function(p:string,c:string,t:boolean) {
        dataService().Area.getAllArea(p,c,t).then((resArea)=>{
            // console.info('resArea',resArea);
            this.endProvinceList=resArea.province;
            this.endCityList = resArea.city;//市
            this.endAreaList= resArea.county;//区
        })
    }
    //发货地址 点击省 触发
    changeStarProvince=function(){
        this.getStarProvinceList();
    }
     getStarProvinceList=function(){
         this.starCity="";//市
         this.starAreaCity="";//区
         this.starAreaList=[];//区列表为空 
        if (this.starProvince === null || this.starProvince == "" || this.starProvince == undefined) {
            this.starProvince = -1;
        }
        dataService().Area.getCity(this.starProvince).then((res)=>{
            this.starCityList=res.list;
        },(rej)=>{
            // console.error("areaApiService.provincecode error: ", rej);
        })
     }
    //发货地址 点击市 触发
    changeCity=function(){
        this.getCityList();
    }
    getCityList=function(){
        this.starAreaCity='';//区
        if (this.starCity === null || this.starCity == "" || this.starCity == undefined) {
            this.starCity = -1;
        }
        dataService().Area.getCountry(this.starCity).then((res)=>{
            this.starAreaList=res.list;
        },(rej)=>{
            // console.error("areaApiService.provincecode error: ", rej);
        })
    }
    //收货地址 点击 省触发
    changeEndProvince=function(){
        this.getEndProvinceList();
    }
    getEndProvinceList=function(){
        this.endCity="";//市
        this.endArea='';//区
        this.endAreaList=[];//区列表为空
        if (this.endProvince === null || this.endProvince == "" || this.endProvince == undefined) {
            this.endProvince = -1;
        }
        dataService().Area.getCity(this.endProvince).then((res)=>{
            this.endCityList=res.list;
        },(rej)=>{
            // console.error("areaApiService.provincecode error: ", rej);
        })
    }
    //收货地址点击市 触发
    changeEndCity=function(){
        this.getEndCityList();
    }
    getEndCityList=function(){
        this.endArea='';//区
        if (this.endCity === null || this.endCity == "" || this.endCity == undefined) {
            this.endCity = -1;
        }
        dataService().Area.getCountry(this.endCity).then((res)=>{
            this.endAreaList=res.list;
        },(rej)=>{
            // console.error("areaApiService.provincecode error: ", rej);
        })
    }
    @Watch('[starCityList,endCityList,endAreaList,starAreaList,goodsNameDropDown]')
    changeValid(){
        // console.info('endAreaList:',this.endAreaList);
        // console.info('starAreaList:',this.starAreaList);
        // console.info('goodsNameDropDown:',this.goodsNameDropDown);
        //验证
        this.validFun();
    }
    validFun=function() {
        // console.info('this.inquiryId',this.inquiryId);
        // console.info('this.name',this.name);
        // if( this.inquiryId!=="undefined"&& this.inquiryId && this.name!=='add'){
            var self = this
            this.$validate(true,  ()=> {
                // console.log('validate done !!')
                if (this.$validation.valid) {
                    // console.info('self.$validation.valid',self.$validation.valid);
                }
            });
        // }
    }
    //addInquiryChild
    addInquiryChild=function(childValid){
        // var self = this
        // this.$validate(true,  ()=> {
            // console.log('validate done !!')
            // if (self.$validation.valid) {
            // e.preventDefault()验证成功
                // console.info("self.$validation.invalid",self.$validation.invalid);
                if(childValid){
                    var startTime =new Date(this.plannedArrivalTime);
                    var endTime =new Date(this.plannedDeliveryTime);
                    if(startTime.getTime()>=endTime.getTime()){
                        bootbox.alert("发货时间需小于到货时间！");
                    }else{
                        // console.info('yvbnm');
                        var itemIndex =Math.round(Math.random() * 10000).toString();
                        var destinationAddress=this.endProvinceList.filter(t=>t.value==this.endProvince)[0].text+this.endCityList.filter(t=>t.value==this.endCity)[0].text+this.endAreaList.filter(t=>t.value==this.endArea)[0].text+this.endAddress
                        var originAddress=this.starProvinceList.filter(t => t.value == this.starProvince)[0].text+this.starCityList.filter(t=>t.value==this.starCity)[0].text+this.starAreaList.filter(t => t.value == this.starAreaCity)[0].text+this.startAddress;
                        var goodsTypeName=this.goodsTypeDropDown? this.goodsTypeDropDown.filter(t => t.id == this.goodsTypeId)[0].name:"";
                        var goodsName= this.goodsNameDropDown? this.goodsNameDropDown.filter(t => t.id == this.goodsId)[0].name:"";
                        var carType=this.carTypeDropDown.filter(t => t.value == this.carType)[0].text;
                        var carLength=this.carLengthDropDown.filter(t => t.value == this.carLength)[0].text;
                        var goodsQuantity =this.goodsQuantityUnitDropDown.filter(t => t.value == this.goodsQuantityUnit)[0].text
                        this.inquiryChildList.push({
                            "destination": {
                                "province": this.endProvince,
                                "city": this.endCity,
                                "county": this.endArea,
                                "details": this.endAddress
                            },
                            "destinationAddress": destinationAddress,//
                            "origin": {
                                "province": this.starProvince,
                                "city": this.starCity,
                                "county": this.starAreaCity,
                                "details": this.startAddress
                            },
                            "originAddress": originAddress,//
                            "foreArrivalTime": this.plannedArrivalTime,//发货
                            "foreDeliveryTime": this.plannedDeliveryTime,//到货
                            "goodsTypeId": this.goodsTypeId,
                            "goodsTypeName": goodsTypeName,//
                            "goodsId": this.goodsId,
                            "goodsName": goodsName,//
                            "quantityOfGoods": this.goodsQuantity,
                            "goodsUnit": this.goodsQuantityUnit,
                            "vehicleType": this.carType,
                            "carLength": this.carLength,
                            "carriageWay": this.carrierCategory,
                            "loadingEffect": this.loadingEffect,
                            "index":itemIndex
                            }
                        )
                        var inquiryChildItem= {shipAddress:originAddress, 
                            deliveryAddress:destinationAddress,
                            goodsName:goodsName,
                            goodsQuantity:this.goodsQuantity+ goodsQuantity,
                            plannedDeliveryTime:this.plannedArrivalTime,
                            plannedArrivalTime:this.plannedDeliveryTime,
                            carType:carType,
                            carLength:carLength,
                            index:itemIndex
                        };
                        this.tableData.push(inquiryChildItem);

                    }
                    
                }
            // }
        // })
    }
    //选择文件触发
    onFileChange=function(e) {
        // console.info('testImageUpload:',e);
        // var files = e.target.files || e.dataTransfer.files;
        var files = e.target.files;
        if (files.length > 0) {
            for(var i=0;i<files.length;i++){
                // if (!/image\/(gif|jpeg|jpg|png|bmp)/.test(files[i].type)){
                //     alert("请选择图片格式文件");
                // } else {
                    // if (files[i].size > 1048576) {
                    //     alert("上传图片大小需小于1M!");
                    // } else {
                        var selectedFileVehicleLicense = files[i];

                        var imageName=Math.round(Math.random() * 10000).toString();
                        // console.info("imageName",imageName);
                        var objUrl = this.getObjectURL(files[i]);;
                        files[i].id=imageName;
                        files[i].path=objUrl;
                        files[i].showStatus=true;
                        files[i].uploadState=false;
                        // files[i].submitUrl=this.handleFileSelectfunc(selectedFileVehicleLicense.name);
                        // var submitVehicleLicenseUrl = this.handleFileSelectfunc(selectedFileVehicleLicense.name);
                        this.imageLists.push(files[i]);
                        if(this.imageLists.length>0){
                            $('#inquiryAdd_uploadAll').removeAttr('disabled');
                        }
                        // console.info('files:',this.imageLists);
                    // }//end if 图片大小
                // }//end if 是否选择文件格式：图片
            }
        }//end if 是否已选择文件控制
    }
    //询价发布
    inquirySave=function(enableInquiryReleaseAdd){
        // console.info("enableInquiryReleaseAdd:",enableInquiryReleaseAdd);
        if(enableInquiryReleaseAdd){
            var submitUploadedFiles=[];
            // this.imageLists=[{submitUrl:"https://sinostoragedev.blob.core.chinacloudapi.cn/realname-container/DrivingLicense-ec52630a-5ff0-4da2-9fc7-50abf001fa60.jpg"}];
            this.submitImageLists.forEach((item)=>{
                submitUploadedFiles.push(
                    {
                        "id": null,
                        "name": item.fileName,
                        "path": item.submitUrl,
                        "tag": null
                    }
                )
            })
            // this.imageLists[].submitUrl 
            var submitInquiry={
                "urgency": this.urgency,
                "urgencyUnit": this.urgencyUnit,
                // "cspInquiryTime": this.inquiryTime,
                "clientId": this.enterpriseid,
                "clientName": this.customerUnit,
                "customerId": this.customerId,
                "attachmentRemarks": this.attachmentDetails,
                "items":this.inquiryChildList,
                "content": this.content,
                "attachmentList": submitUploadedFiles,
                "operatorId": 0
            }
            bootbox.confirm("确认发布询价吗？",(bootboxResult)=>{
                if(bootboxResult){
                    // console.info('inquiryChildList',this.inquiryChildList);
                    for(var i=0;i<this.inquiryChildList.length;i++){
                        delete this.inquiryChildList[i].index;
                    }
                    // console.info('inquiryChildList111',this.inquiryChildList);
                    //dataService().CspInquiry.addCspInquiry().then((res)=>{
                    //})

                    dataService().CspInquiry.addCspInquiry(submitInquiry).then((res)=>{
                        // console.info('success:',res);
                        if(res.success){
                            router.go('../inquiryReleaseManage');
                        }else{
                            var error:string = res.errorMessage;
                            bootbox.alert(error);
                        }
                    },(err)=>{
                        // console.info('error:',err);
                    })
                }else{
                    return;
                }
            });
        }else{
            return;
        }
    }
    //前往该询价单
    linkToInquiryDetail=function(){
        this.inquiryChildIdLinkTo;
        router.go('../inquiryCheck?id='+this.inquiryChildIdLinkTo);
    }
    handleFileSelect=function(e){
        var files = e.target.files;
        if (files.length > 0) {
            for(var i=0;i<files.length;i++){
                // if (!/image\/(gif|jpeg|jpg|png|bmp)/.test(files[i].type)){
                //     alert("请选择图片格式文件");
                // } else {
                    // if (files[i].size > 1048576) {
                    //     alert("上传图片大小需小于1M!");
                    // } else {
                        var selectedFileVehicleLicense = files[i];

                        var imageName=Math.round(Math.random() * 10000).toString();
                        // console.info("imageName",imageName);
                        var objUrl = this.getObjectURL(files[i]);
                        files[i].id=imageName;
                        files[i].path=objUrl;
                        // files[i].submitUrl=this.handleFileSelectfunc(selectedFileVehicleLicense.name);
                        // var submitVehicleLicenseUrl = this.handleFileSelectfunc(selectedFileVehicleLicense.name);
                        this.imageLists.push(files[i]);
                        if(this.imageLists.length>0){
                            $('#inquiryAdd_uploadAll').removeAttr('disabled');
                        }
                        // console.info('files:',this.imageLists);
                    // }//end if 图片大小
                // }//end if 是否选择文件格式：图片
            }
        }//end if 是否已选择文件控制
    };
    
     handleFileSelectfunc=(name)=> {
        //  dataService().Storage.AquireStorageSharedSigniture().then((res)=>{
            // this.sasUrl=res.storageSharedSigniture;
            var baseUrl = this.sasUrl;
            var indexOfQueryStart = baseUrl.indexOf("?");
            // $('#enlargeImage' + imageName).attr('href', objUrl);

            var today = new Date();
            // var formatDate = $filter('date')(today, 'yyyyMMddHHmms');
            var formatDate='';
            var rr = name.indexOf(".");
            name = formatDate + Math.round(Math.random() * 10000).toString() + name.substring(rr);
            return baseUrl.substring(0, indexOfQueryStart) + '/' + name + baseUrl.substring(indexOfQueryStart);
            // })
        
    };
    //建立一個可存取到該file的url
    getObjectURL=(file)=> {
        var urlImg = null;
        if (window.URL != undefined) { // mozilla(firefox)
            urlImg = window.URL.createObjectURL(file);
        } 
        return urlImg;
    }
    

}
